//
//  ZQNetWorkManage+Extension.swift
//  新浪微博
//
//  Created by huami on 2019/11/19.
//  Copyright © 2019 huami. All rights reserved.
//

import Foundation

extension ZQNetWorkManager {
    /// 请求微博数据
    /// - Parameters:
    ///   - since_id: 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 完成回调【list: 微博字典数组/是否成功】
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String: AnyObject]]?, _ isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"

        let params = ["since_id": "\(since_id)",
                      "max_id": "\(max_id > 0 ? max_id - 1 : 0)"] as [String: AnyObject]

        tokenRequest(urlString: urlString, params: params) { json, success in
            guard let json = json else {
                return
            }

            let result = json["statuses"] as! [[String: AnyObject]]
            completion(result, success)
        }
    }

    func unreadCount(completion: @escaping (_ count: Int) -> ()) {
        guard let uid = userAccount.uid else {
            return
        }

        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"

        let params = ["uid": uid]
        tokenRequest(urlString: urlString, params: params as [String: AnyObject]) { json, _ in
            let count = json?["status"] as? Int
            completion(count ?? 0)
        }
     }
}

extension ZQNetWorkManager {
    func laodUserInfo(completion: @escaping(_ dict: [String: Any ])->()) {
        // 加载当前用户信息 - 用户登录后立即执行
        guard let uid = userAccount.uid else {
                   return
               }

        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid": uid]

        // 发起网络请求
        tokenRequest(urlString: urlString, params: params as [String : AnyObject]) { (json, isSuccess) in
            // 完成回调
            completion((json as? [String: Any]) ?? [:])
        }
    }
}

extension ZQNetWorkManager {
    func loadAccessToken(code: String, completion: @escaping(_ isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"

        let params: [String: String] = ["client_id": WBAppKey,
                                        "client_secret": WBAppSecre,
                                        "grant_type": "authorization_code",
                                        "code": code,
                                        "redirect_uri": WBRedirectURI]

        request(
            method: .POST,
            urlString: urlString,
            params: params as [String: AnyObject]
        ) { json, _ in
            self.userAccount.yy_modelSet(with: json as? [String: AnyObject] ?? [:])
            print(self.userAccount)

            self.laodUserInfo { (dict) in
                print(dict)

                // 使用字典设置用户信息
                self.userAccount.yy_modelSet(with: dict)

                // 将用户数据进行保存
                 self.userAccount.saveAcount()

                // 加载完成再回调
                completion(true)
            }
        }
    }
}
